rm(list=ls(all=TRUE))
setwd("~/Dropbox/Apps/ShareLaTeX/Minimal Effects/replication/data")

library(foreign)
library(tables)
library(plyr)
library(doBy)
library(reshape2)
library(ggplot2)

data <- read.dta("ED_contactrecall.dta")

sem <- function(x) sd(x)/sqrt(length(x))

total.n <- nrow(data)
canvassed.n <- nrow(data[data$canvassed == 1,])
not.canvassed.n <- nrow(data[data$canvassed == 0,])

caption <- paste0("Data comes from an Election Day survey in which respondents were asked their recall of campaign contact. We present mean recall rates and the standard error of the mean for multiple types of campaign contact. ",
                  total.n, " people responded, ", canvassed.n, " were canvassed by the partner organization and ",
                  not.canvassed.n, " were not canvassed. This table shows the relative infrequency of personal contact relative to other types of campaign activities.")

latex(tabular(Factor(canvassed, name = "Canvassed?", levelnames = c("No", "Yes")) + Hline() + 1 ~ Format(digits=1)
              *(Heading("In Person")*in_person + 
                Heading("Phone")*phone +
                Heading("Mail")*letter +
                Heading("TV")*tv +
                Heading("Online")*online +
                Heading("Radio")*radio)
              *(Heading("Mean")*mean +
                Heading("SE")*sem),
              data = data), options = list(bottomrule = paste0("\\caption{", caption, "}")))

df <- summaryBy(in_person + phone + letter + tv + online + radio ~ canvassed, data = data, 
          m = mean(x))
means.long <- melt(df,id.vars="canvassed")
means.long$variable <- revalue(means.long$variable, c("in_person.mean"="In Person", "phone.mean"="Phone",
                               "letter.mean" = "Mail",
                               "tv.mean" = "TV",
                               "online.mean" = "Online",
                               "radio.mean" = "Radio"))

pdf('../figures/recall.pdf', width = 7, height = 6)
ggplot(means.long,aes(x = variable,y = value,fill = factor(canvassed)))+
  geom_bar(stat="identity",position="dodge")+
  scale_fill_discrete(name="Canvassed?",
                      breaks=c(0, 1),
                      labels=c("No", "Yes")) +
  xlab("Contact Mode")+ylab("Mean Recall Percentage") +
  theme_bw()
dev.off()
